import React, { Suspense } from 'react';
import { 
  createBrowserRouter, 
  RouterProvider, 
  Navigate,
  Outlet,
  useRouteError,
  isRouteErrorResponse
} from 'react-router-dom';
import { Spin, Button } from 'antd';
import { routes, ROUTE_PATHS, type IAppRouteObject } from './routes';
import { handleRouteError, useRouteGuard } from './guards';
import { MainLayout } from '@/components/layout';
import { ErrorBoundary } from '@/components/common';

/**
 * 路由加载组件
 * @description 在懒加载组件时显示的加载状态
 */
const RouteLoading: React.FC = () => (
  React.createElement('div', { className: "flex items-center justify-center min-h-[200px]" },
    React.createElement(Spin, { size: "large", tip: "页面加载中..." })
  )
);

/**
 * 路由错误组件
 * @description 处理路由级别的错误
 */
const RouteErrorBoundary: React.FC = () => {
  const error = useRouteError();
  
  React.useEffect(() => {
    if (error) {
      handleRouteError(
        error instanceof Error ? error : new Error('未知路由错误'),
        window.location.pathname
      );
    }
  }, [error]);

  if (isRouteErrorResponse(error)) {
    return (
      <div className="flex flex-col items-center justify-center min-h-[400px] p-8">
        <h1 className="text-4xl font-bold text-gray-600 mb-4">
          {error.status}
        </h1>
        <p className="text-lg text-gray-500 mb-6">
          {error.status === 404 ? '页面未找到' : '页面加载失败'}
        </p>
        <p className="text-sm text-gray-400 mb-8">
          {error.statusText || error.data?.message || '请检查URL是否正确'}
        </p>
        <button
          onClick={() => window.location.href = ROUTE_PATHS.HOME}
          className="px-6 py-2 bg-blue-500 text-white rounded hover:bg-blue-600 transition-colors"
        >
          返回首页
        </button>
      </div>
    );
  }

  return (
    <div className="flex flex-col items-center justify-center min-h-[400px] p-8">
      <h1 className="text-2xl font-bold text-red-600 mb-4">
        页面加载出错
      </h1>
      <p className="text-gray-600 mb-6">
        抱歉，页面加载时发生了错误
      </p>
      <button
        onClick={() => window.location.reload()}
        className="px-6 py-2 bg-blue-500 text-white rounded hover:bg-blue-600 transition-colors mr-4"
      >
        重新加载
      </button>
      <button
        onClick={() => window.location.href = ROUTE_PATHS.HOME}
        className="px-6 py-2 bg-gray-500 text-white rounded hover:bg-gray-600 transition-colors"
      >
        返回首页
      </button>
    </div>
  );
};

/**
 * 布局路由组件
 * @description 包含主布局的路由容器
 */
const LayoutRoute: React.FC = () => {
  // 在Router内部使用路由守卫
  useRouteGuard();

  return (
    <MainLayout>
      <ErrorBoundary>
        <Suspense fallback={<RouteLoading />}>
          <Outlet />
        </Suspense>
      </ErrorBoundary>
    </MainLayout>
  );
};

/**
 * 转换路由配置为React Router格式
 * @param appRoutes 应用路由配置
 * @returns React Router路由配置
 */
const transformRoutes = (appRoutes: IAppRouteObject[]): any[] => {
  return appRoutes.map(route => ({
    path: route.path,
    element: route.element ? React.createElement(route.element) : undefined,
    errorElement: <RouteErrorBoundary />,
    children: route.children ? transformRoutes(route.children) : undefined
  }));
};

/**
 * 创建路由器配置
 */
const router = createBrowserRouter([
  {
    path: '/',
    element: <LayoutRoute />,
    errorElement: <RouteErrorBoundary />,
    children: [
      // 根路径重定向到首页
      {
        index: true,
        element: <Navigate to={ROUTE_PATHS.HOME} replace />
      },
      // 应用路由
      ...transformRoutes(routes),
      // 404页面
      {
        path: '*',
        element: (
          <div className="flex flex-col items-center justify-center min-h-[400px] p-8">
            <h1 className="text-4xl font-bold text-gray-600 mb-4">404</h1>
            <p className="text-lg text-gray-500 mb-6">页面未找到</p>
            <p className="text-sm text-gray-400 mb-8">
              您访问的页面不存在，请检查URL是否正确
            </p>
            <button
              onClick={() => window.location.href = ROUTE_PATHS.HOME}
              className="px-6 py-2 bg-blue-500 text-white rounded hover:bg-blue-600 transition-colors"
            >
              返回首页
            </button>
          </div>
        )
      }
    ]
  }
]);

/**
 * 应用路由提供者组件
 * @description 为整个应用提供路由功能
 */
export const AppRouter: React.FC = () => {
  return <RouterProvider router={router} />;
};

/**
 * 路由工具函数
 */
export const routerUtils = {
  /**
   * 获取当前路由路径
   */
  getCurrentPath: () => window.location.pathname,
  
  /**
   * 检查是否为指定路径
   */
  isCurrentPath: (path: string) => window.location.pathname === path,
  
  /**
   * 检查是否匹配路径模式
   */
  matchesPath: (pattern: string) => {
    const regex = new RegExp(pattern.replace(/\*/g, '.*'));
    return regex.test(window.location.pathname);
  },
  
  /**
   * 构建查询参数字符串
   */
  buildQuery: (params: Record<string, string | number | boolean>) => {
    const searchParams = new URLSearchParams();
    Object.entries(params).forEach(([key, value]) => {
      searchParams.set(key, String(value));
    });
    return searchParams.toString();
  },
  
  /**
   * 解析查询参数
   */
  parseQuery: (search?: string) => {
    const params = new URLSearchParams(search || window.location.search);
    const result: Record<string, string> = {};
    params.forEach((value, key) => {
      result[key] = value;
    });
    return result;
  }
};

// 导出路由相关的所有内容
export * from './routes';
export * from './guards';
export { router };
export default AppRouter;